
import MyModal from "@/components/MyModal";
import { IDCardReg, PhoneReg } from "@/constants/reg";
import { getOptionalTime, orderRoom } from "@/services/customer/customer";
import { getUerInfo } from "@/utils/info";
import { useBoolean, useRequest } from "ahooks";
import { DatePicker, Form, Input, message } from "antd";
import dayjs from "dayjs";
import { useEffect, useState } from "react";
const { RangePicker } = DatePicker;
const  isBetween = require('dayjs/plugin/isBetween')
dayjs.extend(isBetween)
export default ({ open, close, roomInfo,refresh }) => {
  const [form] = Form.useForm();
  const [loading, { toggle: toggleLoading }] = useBoolean(false);
  const today = dayjs(); //今天
  const timeLong = 30; //预约时间
  const roomId = roomInfo.roomId;
  const time = Form.useWatch("time", form);
  const [roomPrice, setRoomPrice] = useState(void 0); //房屋单价
  const onOk = async () => {
    const values = await form.validateFields();
    values.stayStartByTime = dayjs(values.time[0].valueOf()).format(
      "YYYY-MM-DD"
    );
    values.stayEndtByTime = dayjs(values.time[1].valueOf()).format(
      "YYYY-MM-DD"
    );
    values.orderCheckInTime = dayjs(values.time[0].valueOf()).format(
      "YYYY-MM-DD"
    );
    values.roomId = roomInfo.roomId;
    values.orderAccount = getUerInfo().account;
    delete values.time;
    toggleLoading();
    try {
      const res = await orderRoom({ ...values });
      message.success("办理预定成功," + res);
      close();
      refresh();
    } finally {
      toggleLoading();
    }
  };
  useEffect(() => {
    let money = void 0;
    if (time) {
      const days = time?.[1].diff(time?.[0], "day");
      money = days === 0 ? roomPrice : roomPrice * days;
    }
    form.setFieldValue("houseCosts", money);
  }, [time, roomPrice]);
  const handleOpen = () => {
    setRoomPrice(roomInfo.roomPrice);
  };
  useEffect(() => {
    handleOpen();
  }, [open, roomInfo]);
  const { data: optionalTime } = useRequest(
    () => {
      if (!roomId) return [];
      return getOptionalTime({ roomId });
    },
    {
      refreshDeps: [roomId],
    }
  );

  const isDisableDate = (d) =>{
    return d.isBefore(today) || d.isAfter(today.add(timeLong, "day"))||optionalTime.includes(dayjs(d).format("YYYY-MM-DD"))
  }
  return (
    <MyModal
      title={"预订客房"}
      open={open}
      close={close}
      onOk={onOk}
      confirmLoading={loading}
    >
      <Form form={form} wrapperCol={{ span: 24 }} layout="vertical">
        <Form.Item
          name="realName"
          rules={[
            {
              required: true,
            },
          ]}
          label="姓名"
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          name="tel"
          rules={[
            {
              required: true,
            },
            {
              pattern: PhoneReg,
              message: "请输入正确的手机号码",
            },
          ]}
          label="电话"
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          name="identifyNum"
          rules={[
            {
              required: true,
            },
            {
              pattern: IDCardReg,
              message: "请输入正确的身份证号码",
            },
          ]}
          label="身份证号码"
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          label="房间类型"
        >
          {roomInfo?.roomType}
        </Form.Item>
        <Form.Item
          label="房间单价(元/天)"
        >
          {roomInfo?.roomPrice}
        </Form.Item>
        <Form.Item
          name="time"
          label="入住时间-退房时间"
          required
          rules={[
            {
              validator: (rule, value) => {
                if (value[0] && value[1] && !value[0].isBefore(value[1])) {
                  return Promise.reject("退房时间不能等于入住时间");
                }
                if(optionalTime?.find(i=>dayjs(i).isBetween(value[0],value[1]))){
                  return Promise.reject("预定时间不能包含已被预定时间")
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <RangePicker
          allowClear={false}
            disabledDate={(d) =>
              isDisableDate(d)
            }
          />
        </Form.Item>
        {!!time && (
          <Form.Item
            name="houseCosts"
            rules={[
              {
                required: true,
              },
            ]}
            label="金额"
          >
            <Input
              readOnly
              style={{ width: "200px" }}
              prefix="￥"
              suffix="RMB"
            />
          </Form.Item>
        )}
        {!!time && (
          <Form.Item label="预计线下办理入住时间">
            {dayjs(time[0]).format("YYYY-MM-DD")}
          </Form.Item>
        )}
      </Form>
    </MyModal>
  );
};
